package com.vectz.mgt.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import com.vectz.mgt.model.Entity;
import com.vectz.mgt.model.EntityOverview;
import com.vectz.mgt.util.Log;
import com.vectz.mgt.util.Util;

/**
 * @author ai-t.vn
 * 
 */
public class IndexPageCodegenAction {
	ArrayList<Entity> listField=null;
	EntityOverview table = null;
	String outputFolder = "";
	private final String fieldLinkMark = "<!--EntityLink-->";
	
	public IndexPageCodegenAction(ArrayList<Entity> listField, EntityOverview table,
			String outputFolder) throws Exception {
		this.listField = listField;
		this.table = table;
		this.outputFolder = outputFolder;
		genernateIndexFile();
	}

	/*
	 * Generate main.xhtml file
	 */
	public void genernateIndexFile() throws Exception {
			String mainFilePath = new File("").getAbsolutePath()
				+ System.getProperty("file.separator") + "templ" 
				+ System.getProperty("file.separator") + "main.xhtml";
				
			String tmplFormContent = Util.readTextFileContent(mainFilePath);
			
			String fieldLink = new StringBuilder()
					.append("<tr><td><li><a href=\"")
					.append(table.getDestScreenPath().substring(table.getDestScreenPath().lastIndexOf("\\")+1,
							table.getDestScreenPath().length()))
					.append("/")
					.append(Util.lowerCaseFirstChar(table.getName()))
					.append("List.seam\">")
					.append(Util.upperCaseFirstChar(table.getName()))
					.append("</a></li></td></tr>\n").toString();
			//get index of <!--EntityLink--> 
			int linkIndex = tmplFormContent.indexOf(fieldLinkMark);
			if(linkIndex!=-1)
				tmplFormContent = tmplFormContent.substring(0,linkIndex ) 
				+ fieldLink 
				+ tmplFormContent.substring(linkIndex , tmplFormContent.length()) ;
			// get main.xhtml file location
			String fileLocation = new StringBuffer().append(outputFolder)
			.append(System.getProperty("file.separator"))
			.append("WebContent")
			.append(System.getProperty("file.separator"))
			.append("main.xhtml").toString();
			
			Util.writeJavaFile(fileLocation,tmplFormContent);
			//update fieldLink to current main.xhtml file
			Util.writeJavaFile(mainFilePath, tmplFormContent);
			Log.log("Finish generate main.xhtml file to:"+ fileLocation);
	}

	
}
